﻿Imports System.Data.SqlClient

Public Class RolDAO

    Public Function insertar(ByVal gato As Rol) As Rol
        Try
            Dim cn As New SqlConnection(ConexionBD.obtenerCadenaConexion())
            cn.Open()

            Dim sql = "INSERT INTO ROL (NOMBRE, DESCRIPCION) VALUES (@VALOR1, @VALOR2)"

            Dim cmd As New SqlCommand(sql, cn)
            cmd.Parameters.AddWithValue("@VALOR1", gato.nombre)
            cmd.Parameters.AddWithValue("@VALOR2", gato.descripcion)

            Dim afectados = cmd.ExecuteNonQuery

            If afectados <> 1 Then
                Throw New DAOExcepcion("RolDAO: No insertó")
            End If

            ' LEER EL ULTIMO ID
            sql = "SELECT @@IDENTITY"
            cmd = New SqlCommand(sql, cn)
            Dim dr As SqlDataReader
            dr = cmd.ExecuteReader()
            If dr.Read Then
                gato.idRol = CType(dr(0), Integer)
            End If

            dr.Close()
            cn.Close()

        Catch ex As Exception
            Throw New DAOExcepcion(ex.ToString)
        End Try

        Return gato

    End Function


    Public Function listar() As Collection
        Dim lista As New Collection

        Try
            Dim cn As New SqlConnection(ConexionBD.obtenerCadenaConexion())
            cn.Open()

            Dim sql = "SELECT IDROL, NOMBRE, DESCRIPCION FROM ROL"
            Dim cmd As New SqlCommand(sql, cn)

            Dim dr As SqlDataReader
            dr = cmd.ExecuteReader()
            While dr.Read
                Dim gato As New Rol
                gato.idRol = dr(0).ToString
                gato.nombre = dr(1).ToString
                gato.descripcion = dr(2).ToString
                

                lista.Add(gato)
            End While

            dr.Close()
            cn.Close()

        Catch ex As SqlException
            Throw New DAOExcepcion(ex.ToString)
        End Try

        Return lista
    End Function





End Class